package com.tao.utilslib.ui;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;

import com.tao.utilslib.data.Base64Util;
import com.tao.utilslib.data.Obj;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class BitmapUtils {

    public static void saveBitmap2Local(String path, Bitmap bitmap) {
        saveBitmap2Local(path, bitmap, Bitmap.CompressFormat.PNG);
    }

    public static void saveBitmap2Local(String path, Bitmap bitmap, Bitmap.CompressFormat format) {
        // 创建文件对象，用来存储新的图像文件
        File file = new File(path);
        // 创建文件
        try {
            if (file.exists()) {
                file.delete();
            } else {
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
            // 定义文件输出流
            FileOutputStream fOut = new FileOutputStream(file);
            // 将bitmap存储为jpg格式的图片
            bitmap.compress(format, 100, fOut);

            fOut.flush();// 刷新文件流
            fOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public static Bitmap getDiskBitmap(String pathString) {
        Bitmap bitmap = null;
        try {
            File file = new File(pathString);
            if (file.exists()) {
                bitmap = BitmapFactory.decodeFile(pathString);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }

        return bitmap;
    }


    public static Bitmap runInPreviewFrame(byte[] data, Camera camera) {
        // camera.setOneShotPreviewCallback(null);
        // 处理data
        Bitmap bitmap = null;
        if (camera != null) {
            Camera.Size previewSize = camera.getParameters().getPreviewSize();// 获取尺寸,格式转换的时候要用到
            BitmapFactory.Options newOpts = new BitmapFactory.Options();


            newOpts.inJustDecodeBounds = true;
            YuvImage yuvimage = new YuvImage(data, ImageFormat.NV21,
                    previewSize.width, previewSize.height, null);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            yuvimage.compressToJpeg(new Rect(0, 0, previewSize.width,
                    previewSize.height), 80, baos);// 80--JPG图片的质量[0-100],100最高

            byte[] rawImage = baos.toByteArray();

            // 将rawImage转换成bitmap

            BitmapFactory.Options options = new BitmapFactory.Options();

            options.inPreferredConfig = Bitmap.Config.RGB_565;

            bitmap = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length, options);
        }

        return bitmap;
    }

    public static Bitmap decodeBitmapBase64(String base64) {
        Bitmap bitmap = null;
        try {
            bitmap = decodeBitmap(Base64Util.decode(base64));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public static Bitmap decodeBitmap(byte[] data) {
        if (Obj.isNULL(data) || data.length == 0)
            return null;
        return BitmapFactory.decodeByteArray(data, 0, data.length);
    }

    public static Bitmap decodeBitmapPath(String path) {
        if (Obj.isNULL(path) || !new File(path).exists())
            return null;
        return BitmapFactory.decodeFile(path);
    }

    public static Bitmap decodeBitmapPath(String path, int qualty) {
        return decodeBitmap(bm2Bytes(decodeBitmapPath(path), Bitmap.CompressFormat.PNG, qualty), Bitmap.CompressFormat.PNG);
    }

    public static Bitmap decodeBitmapBase64(String base64, Bitmap.CompressFormat format) {
        Bitmap bitmap = null;
        try {
            bitmap = decodeBitmap(Base64Util.decode(base64), format);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public static byte[] reduceImage(byte[] data, int qualty) {
        return bm2Bytes(decodeBitmap(data), Bitmap.CompressFormat.PNG, qualty);
    }

    public static Bitmap decodeBitmap(byte[] data, int qualty) {
        return decodeBitmap(bm2Bytes(decodeBitmap(data), Bitmap.CompressFormat.PNG, qualty));
    }

    public static Bitmap decodeBitmap(byte[] data, Bitmap.CompressFormat format) {
        if (Obj.isNULL(data) || data.length == 0)
            return null;
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(format, 100, stream);
        byte[] bytes = stream.toByteArray();
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    public static byte[] bm2Bytes(Bitmap bitmap) {
        return bm2Bytes(bitmap, Bitmap.CompressFormat.PNG, 100);
    }

    public static byte[] bm2Bytes(Bitmap bitmap, Bitmap.CompressFormat format, int qualty) {
        if (bitmap == null)
            return null;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            boolean compress = bitmap.compress(format, qualty, stream);
            if (compress) {
                return stream.toByteArray();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /*
     *
     * @Title: bitmapRotation
     * @Description: 图片旋转
     * @param bm
     * @param orientationDegree
     * @return Bitmap
     * @throws
     */
    public Bitmap bitmapRotation(Bitmap bm, final int orientationDegree) {

        Matrix m = new Matrix();
        m.setRotate(orientationDegree, (float) bm.getWidth() / 2,
                (float) bm.getHeight() / 2);
        float targetX, targetY;
        if (orientationDegree == 90) {
            targetX = bm.getHeight();
            targetY = 0;
        } else if (orientationDegree == 270) {
            targetX = 0;
            targetY = bm.getWidth();
        } else {
            targetX = bm.getHeight();
            targetY = bm.getWidth();
        }

        final float[] values = new float[9];
        m.getValues(values);

        float x1 = values[Matrix.MTRANS_X];
        float y1 = values[Matrix.MTRANS_Y];

        m.postTranslate(targetX - x1, targetY - y1);

        Bitmap bm1 = Bitmap.createBitmap(bm.getHeight(), bm.getWidth(),
                Bitmap.Config.ARGB_8888);

        Paint paint = new Paint();
        Canvas canvas = new Canvas(bm1);
        canvas.drawBitmap(bm, m, paint);

        return bm1;
    }

    public static Bitmap rotateBitmap(int degree, Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }

}
